import gLTF from '../threejsimport/jsm/loaders/GLTFLoader'
import { OrbitControls } from '../threejsimport/jsm/controls/OrbitControls'

export default function (canvas, THREE) {
  let GLTFLoader = gLTF(THREE);
  const renderer = new THREE.WebGLRenderer({ canvas:canvas,antialias:true,precision:"highp" });
  console.log("renderer",renderer)
  renderer.shadowMap.enabled = true;

  const fov = 45;
  const aspect = 2;  // the canvas default
  const near = 0.1;
  const far = 100;
  const camera = new THREE.PerspectiveCamera(fov, aspect, near, far);
  camera.position.set(0, 5, 10);

  const controls = new OrbitControls(camera, canvas);
  controls.target.set(0, 0, 0);
  controls.update();

  const scene = new THREE.Scene();
  scene.background = new THREE.Color('#DEFEFF');


  {
    const skyColor = 0xffffff;  // light blue
    const groundColor = 0xB97A20;  // brownish orange
    const intensity = 1;
    const light = new THREE.HemisphereLight(skyColor, groundColor, intensity);
    scene.add(light);
  }

  {
    const color = 0xFFFFFF;
    const intensity = 1;
    const light = new THREE.DirectionalLight(color, intensity);
    light.castShadow = true;
    light.position.set(-250, 800, -850);
    light.target.position.set(-550, 40, -450);

    light.shadow.bias = -0.004;
    light.shadow.mapSize.width = 2048;
    light.shadow.mapSize.height = 2048;

    scene.add(light);
    scene.add(light.target);
    const cam = light.shadow.camera;
    cam.near = 1;
    cam.far = 2000;
    cam.left = -1500;
    cam.right = 1500;
    cam.top = 1500;
    cam.bottom = -1500;

    const cameraHelper = new THREE.CameraHelper(cam);
    scene.add(cameraHelper);
    cameraHelper.visible = false;
    const helper = new THREE.DirectionalLightHelper(light, 100);
    scene.add(helper);
    helper.visible = false;

   

    function updateCamera() {
      
      light.updateMatrixWorld();
      light.target.updateMatrixWorld();
      helper.update();
      light.shadow.camera.updateProjectionMatrix();
      cameraHelper.update();
    }
    updateCamera();
  }

  function frameArea(sizeToFitOnScreen, boxSize, boxCenter, camera) {
    const halfSizeToFitOnScreen = sizeToFitOnScreen * 0.5;
    const halfFovY = THREE.Math.degToRad(camera.fov * .5);
    const distance = halfSizeToFitOnScreen / Math.tan(halfFovY);
    // compute a unit vector that points in the direction the camera is now
    // in the xz plane from the center of the box
    const direction = (new THREE.Vector3())
      .subVectors(camera.position, boxCenter)
      .multiply(new THREE.Vector3(1, 0, 1))
      .normalize();

    // move the camera to a position distance units way from the center
    // in whatever direction the camera was from the center already
    camera.position.copy(direction.multiplyScalar(distance).add(boxCenter));

    // pick some near and far values for the frustum that
    // will contain the box.
    camera.near = boxSize / 100;
    camera.far = boxSize * 100;

    camera.updateProjectionMatrix();

    // point the camera to look at the center of the box
    camera.lookAt(boxCenter.x, boxCenter.y, boxCenter.z);
  }

  function getCurrentTime(){
    var time = Date.parse( new Date() ).toString();//获取到毫秒的时间戳，精确到毫秒
    time = time.substr(0,10);//精确到秒
    return time;
  }

  {
    const gltfLoader = new GLTFLoader();
    console.log("start",getCurrentTime())
    wx.downloadFile({
      url: 'https://shiru.oss-cn-shenzhen.aliyuncs.com/test.gltf',
      success: res => {
        // fileList 是一个有如下结构的对象数组
        // [{
        //    fileID: 'cloud://xxx.png', // 文件 ID
        //    tempFileURL: '', // 临时文件网络链接
        //    maxAge: 120 * 60 * 1000, // 有效期
        // }]
       // console.log(res.fileList)
       console.log("downloadFile",getCurrentTime())
       let tempFilePath = res.tempFilePath;
       if(tempFilePath.indexOf('wxfile://') == 0){
          wx.getFileSystemManager().readFile({
          filePath:tempFilePath,
          encoding:'utf8',
          success:rs =>{
            console.log("readFile",getCurrentTime())
            //console.log(rs)
            gltfLoader.parse(rs.data, "",(gltf) => {
              console.log("parseFileDone",getCurrentTime())
              const root = gltf.scene;
              scene.add(root);
            }, (e) => {
              console.log(e)
            });
          },
          fail:rs=>{}
        })
       }else{
          gltfLoader.load(res.tempFilePath, (gltf) => {
            const root = gltf.scene;
            scene.add(root);
          }, (e) => {
            console.log(e)
          });
       }
        
      },
      fail: console.error
    })
    
  
    // wx.cloud.getTempFileURL({
    //   fileList: ['cloud://cloud1-0gdzvpki0eca8eb4.636c-cloud1-0gdzvpki0eca8eb4-1307787824/列管换热器.gltf'],
    //   success: res => {
    //     // fileList 是一个有如下结构的对象数组
    //     // [{
    //     //    fileID: 'cloud://xxx.png', // 文件 ID
    //     //    tempFileURL: '', // 临时文件网络链接
    //     //    maxAge: 120 * 60 * 1000, // 有效期
    //     // }]
    //     console.log(res.fileList)
    //     gltfLoader.load(res.fileList[0].tempFileURL, (gltf) => {
    //       const root = gltf.scene;
    //       scene.add(root);
    //     }, (e) => {
    //       console.log(e)
    //     });
    //   },
    //   fail: console.error
    // })
    
  }

  function resizeRendererToDisplaySize(renderer) {
    const canvas = renderer.domElement;
    const width = canvas.clientWidth;
    const height = canvas.clientHeight;
    const needResize = canvas.width !== width || canvas.height !== height;
    if (needResize) {
      renderer.setSize(width, height, false);
    }
    return needResize;
  }


  function render(time) {
    time *= 0.001;  // convert to seconds

    if (resizeRendererToDisplaySize(renderer)) {
      const canvas = renderer.domElement;
      camera.aspect = canvas.clientWidth / canvas.clientHeight;
      camera.updateProjectionMatrix();
    }

    renderer.render(scene, camera);

    canvas.requestAnimationFrame(render);
  }

  canvas.requestAnimationFrame(render);
}